import { Component, Injector, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { ConfigModule } from 'src/app/config.module';
import { NavigationEnd, Router } from '@angular/router';
import { Subject, Subscription } from 'rxjs';
import { filter, takeUntil } from 'rxjs/operators';
import { listAnimation } from '../../../../animations/list.animation';
import { BaseUI } from '../../../../common/base';
import { UserService } from '../service/user.service';
import { UserOptionComponent } from '../component/user-option/user-option.component';
import {
    EventKeyEnum,
    EventPublishDTO,
    OptionTypeEnum,
    TableOptionModel
} from '../../../../components/table/table-option/table-option.model';
import { TableComponent } from '../../../../components/table/table.component';
import { ColumnType } from '../../../../components/table/enums/ColumnType';
import { NzTreeNodeOptions } from 'ng-zorro-antd/core/tree/nz-tree-base-node';
import { DateUtil } from '../../../../utils/DateUtil';
import { ResetPwdOptionComponent } from '../component/reset-pwd-option/reset-pwd-option.component';
import { assignRolePage } from '../../../../app-routing.module';


@Component({
    selector: 'app-user',
    templateUrl: './index.component.html',
    styleUrls: ['./index.component.scss'],
    animations: [listAnimation],
})
export class UserComponent extends BaseUI implements OnInit, OnDestroy {
    router$: Subscription;
    onDestroy$: Subject<any> = new Subject<any>();
    constructor(
        public _config: ConfigModule,
        private _router: Router,
        private _injector: Injector,
        public userService: UserService,
    ) {
        super(_injector);
        this.router$ = this._router.events
            .pipe(
                filter((ev) => ev instanceof NavigationEnd),
                takeUntil(this.onDestroy$)
            )
            .subscribe(() => {
            });
    }

    ngOnInit() {
        // this._config.modalContentHeight.height = 'auto';
        // this._config.scrollValue.x = super.getTableWidth();
        this.userService.deptTree().subscribe(res => {
            if (res.code === 200){
                this.treeData = this.convertTreeToList(res.data);
            }
        })
    }

    convertTreeToList(data:any[]): Array<NzTreeNodeOptions> {
        if (!data) return;
        let treeData: NzTreeNodeOptions[] = [];
        data.forEach(node => {
            let treeNode: NzTreeNodeOptions={} as NzTreeNodeOptions;
            treeNode.title = node.label;
            treeNode.expanded = true;
            treeNode.key = node.id;
            treeNode.children = this.convertTreeToList(node.children);
            if (!treeNode.children){
                treeNode.isLeaf = true;
            }
            treeData.push(treeNode);
        })
        return treeData
    }

    ngOnDestroy() {
        this.onDestroy$.complete();
    }


    @ViewChild("mainTable")
    mainTable: TableComponent;

    searchObj:any = {
        pageNum: 1,
        deptId: '',
        deptName:'',
        pageSize: this._config.pageSize,
        name: '',
        phonenumber: '',
        emailNumber: '',
        status: "",
    };

    columnArray = [
        {type: ColumnType.TEXT, name: '用户编号', key: 'userId'},
        {type: ColumnType.TEXT, name: '用户名称', key: 'userName'},
        {type: ColumnType.TEXT, name: '用户昵称', key: 'nickName'},
        {type: ColumnType.TEXT, name: '部门', key: 'dept.deptName'},
        {type: ColumnType.TEXT, name: '手机号码', key: 'phonenumber'},
        {type: ColumnType.SWITCH, name: '状态', key: 'status'},
        {type: ColumnType.TEXT, name: '创建时间', key: 'createTime'},
    ];
    optionModelList: TableOptionModel[] = [
        {
            optionLabel:"编辑",
            optionLabelType: OptionTypeEnum.TEXT,
            eventKey:EventKeyEnum.EDIT
        },
        {
            optionLabel:"删除",
            optionLabelType: OptionTypeEnum.TEXT,
            eventKey:EventKeyEnum.DELETE
        },
        {
            optionLabel:"更多",
            optionLabelType: OptionTypeEnum.MORE,
            eventType:"",
            children:[       {
                optionLabel:"重置密码",
                optionLabelType: OptionTypeEnum.TEXT,
                eventKey:EventKeyEnum.RESET_PASSWORD
            },
                {
                    optionLabel:"分配角色",
                    optionLabelType: OptionTypeEnum.TEXT,
                    eventKey:EventKeyEnum.DISTRIBUTE_ROLE
                },]
        }
    ]

    otherOptionModelList: TableOptionModel[] = [
        {
            optionLabel:"新增",
            optionLabelType: OptionTypeEnum.BUTTON,
            eventKey:EventKeyEnum.ADD,
        }
    ]



    searchList() {
        if (this.mainTable){
            this.mainTable.list();
        }
    }

    keyEnter($event: KeyboardEvent) {
        if($event.key === 'Enter'){
            this.searchList();
        }
    }


    /**
     * 日期选择
     */

    datePick: string[]=[];
    onDatePick() {
        this.searchObj.params = {};
        this.searchObj.params['beginTime'] = DateUtil.formatDate(this.datePick[0],"yyyy-MM-dd");
        this.searchObj.params['endTime'] = DateUtil.formatDate(this.datePick[1],"yyyy-MM-dd");
    }


    /**
     * 部门树相关变量
     */
    treeData: any =[];
    selectedTreeNode(deptId: string){
        this.searchObj.deptId = deptId;
        this.mainTable.list();
    }


    /**
     * 操作弹框
     */
    @ViewChild('userOptionComponent') userOptionComponent: UserOptionComponent;

    optionEvent($event: EventPublishDTO) {
        let data  = $event.publishData;
        switch ($event.eventKey) {
            case EventKeyEnum.EDIT:
                this.userOptionComponent.onModalOpen(data.userId);
                break;
            case EventKeyEnum.DELETE:
                this.userService.delete(data.userId).subscribe(res => {
                    if (res.success) {
                        this.mainTable.list();
                    }
                });
                break;
            case EventKeyEnum.ADD:
                this.userOptionComponent.onModalOpen("");
                break;
            case EventKeyEnum.RESET_PASSWORD:
                this.resetPwdOptionComponent.onModalOpen(data.userId,data.userName);
                break;
            case EventKeyEnum.DISTRIBUTE_ROLE:
                this.router.navigate(['/manage/'+assignRolePage.path,data.userId]).finally()
                break;
        }
    }

    resetSearchObject(){
        this.searchObj = {
            pageNum: 1,
            pageSize: this._config.pageSize,
        };
        this.datePick=[];
    }


    @ViewChild('resetPwdOptionComponent') resetPwdOptionComponent: ResetPwdOptionComponent;


}
